
import { ChangeStateAble } from "./ChangeStateAble";
import { Ai_dataEnum, ThinkType } from "./AIConfig";
import { Perception } from "./Perception";
import IXlsxTransform from "../../cfw/xlsx/IXlsxTransform";
import Utils from "../../cfw/tools/Utils";
import { BaseController } from "../../cfw/mvc/BaseController";

/**
 * 决策树，使用自己的数据表
 */
export class DecisionTree extends BaseController<ChangeStateAble> {

    protected decisionData: IXlsxTransform;
    protected perception: Perception;

    setPerception(perception: Perception) {
        this.perception = perception;
    }

    checkPerception(perceptionType: number, value?: any) {
        return this.perception.action(this.getTarget(), perceptionType, value)
    }

    getPerception() {
        return this.perception;
    }

    

    constructor() {
        super()
    }

    setData(data: IXlsxTransform) {
        this.decisionData = data;
    }




    action(target: ChangeStateAble, decisionID: number) {
        let data = this.decisionData.getRowData(decisionID)
        let flag = false;
        if (data) {
            let perceptionType = data[Ai_dataEnum.condition];
            let type = 0;
            let id: number[] = null;
            flag = this.perception.action(target, perceptionType, data[Ai_dataEnum.cParam])
            if (flag) {
                type = data[Ai_dataEnum.conditionYes]
                id = data[Ai_dataEnum.parm1]
            } else {
                type = data[Ai_dataEnum.conditionNo]
                id = data[Ai_dataEnum.parm2]
            }
            this.judge(type, id)
        } else {
            console.error(' DecisionTree action  data is null decisionID ', decisionID)
        }
        return flag;
    }

    private judge(type: ThinkType, param: number[]) {
        if (type == ThinkType.ACTION) {
            this.doLogic(param)
        } else {
            for (let index = 0; index < param.length; index++) {
                const element = param[index];
                if (this.action(this.getTarget(), element)) {
                    break;//目前仅支持串行，不支持并行。如需支持并行，需要添加是否拦截字段。
                }
            }
        }
    }

    // 50 30 20 : 80 
    private doLogic(param: number[]) {
        if (param.length > 0) {
            let r = Utils.random(0, 100);
            let count = param.length / 2
            for (let index = 0; index < count; index++) {
                let behaveType: number = param[index * 2]
                let random: number = param[index * 2 + 1]
                //
                if (r <= random) {
                    this.getTarget().changeState(behaveType)
                    return;
                }
            }
        }


    }

    think(decisionID: number) {
        this.action(this.getTarget(), decisionID)
    }
}